using Microsoft.Extensions.Logging;
using UniversalAdmin.Application.Services;

namespace UniversalAdmin.Infrastructure.Services;

public class MockEmbeddingService : IEmbeddingService
{
    private readonly ILogger<MockEmbeddingService> _logger;

    public MockEmbeddingService(ILogger<MockEmbeddingService> logger)
    {
        _logger = logger;
    }

    public async Task<float[]> GenerateEmbeddingAsync(string text, bool isQuery = false)
    {
        // 模拟API调用延迟
        await Task.Delay(100);

        // 生成一个简单的基于文本长度和哈希的向量
        var hash = text.GetHashCode();
        var length = text.Length;

        // 创建一个384维的向量（常见的嵌入维度）
        var embedding = new float[384];
        var random = new Random(hash);

        for (int i = 0; i < embedding.Length; i++)
        {
            // 确保生成的值不为0，避免空字节问题
            var value = random.NextDouble() * 2 - 1; // -1 到 1 之间的值
            embedding[i] = (float)(value == 0 ? 0.001f : value);
        }

        // 归一化向量
        var norm = (float)Math.Sqrt(embedding.Sum(x => x * x));
        if (norm > 0)
        {
            for (int i = 0; i < embedding.Length; i++)
            {
                embedding[i] /= norm;
                // 再次确保没有零值
                if (Math.Abs(embedding[i]) < 1e-6f)
                {
                    embedding[i] = 0.001f;
                }
            }
        }

        _logger.LogInformation("Generated mock embedding for text of length {Length}", text.Length);
        return embedding;
    }

    public async Task<List<float[]>> GenerateEmbeddingsAsync(List<string> texts, bool isQuery = false)
    {
        var embeddings = new List<float[]>();

        foreach (var text in texts)
        {
            var embedding = await GenerateEmbeddingAsync(text, isQuery);
            embeddings.Add(embedding);
        }

        return embeddings;
    }
}